package maple.thelittleredbook.content.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import maple.thelittleredbook.content.dto.*;
import maple.thelittleredbook.content.service.ContentOperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import maple.thelittleredbook.common.dto.ApiResponse;
import maple.thelittleredbook.common.service.AuthService;
import maple.thelittleredbook.content.service.ContentService;
import maple.thelittleredbook.logging.annotation.SystemLog;

/**
 * 内容控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/contents")
public class ContentController {

    private final ContentService contentService;
    private final AuthService authService;
    private final ContentOperationLogService operationLogService;

    @Autowired
    public ContentController(ContentService contentService, AuthService authService, ContentOperationLogService operationLogService) {
        this.contentService = contentService;
        this.authService = authService;
        this.operationLogService = operationLogService;
    }

    /**
     * 创建内容
     */
    @PostMapping
    @SystemLog(operation = "创建内容")
    public ResponseEntity<ApiResponse<ContentCreateResponseDTO>> createContent(
            @Valid @ModelAttribute ContentCreateRequestDTO requestDTO) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户创建内容请求，用户ID: {}, 内容类型: {}, 标题: {}",
                userId, requestDTO.getContentType(), requestDTO.getTitle());

        // 调用服务层创建内容，通过DTO的get方法获取参数
        ContentCreateResponseDTO responseDTO = contentService.createContent(
                userId,
                requestDTO.getContentType(),
                requestDTO.getTitle(),
                requestDTO.getTextContent(),
                requestDTO.getCover(),
                requestDTO.getImages(),
                requestDTO.getVideo());

        return ResponseEntity.ok(ApiResponse.success("内容创建成功", responseDTO));
    }

    /**
     * 更新封面
     */
    @PutMapping("/{contentId}/cover")
    @SystemLog(operation = "更新内容封面")
    public ResponseEntity<ApiResponse<String>> updateCover(
            @PathVariable Long contentId,
            @Valid @ModelAttribute CoverUpdateRequestDTO requestDTO) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户更新封面请求，用户ID: {}, 内容ID: {}", userId, contentId);

        contentService.updateCover(contentId, requestDTO.getCover(), userId);
        return ResponseEntity.ok(ApiResponse.success("封面更新任务已提交，正在处理中"));
    }

    /**
     * 更新视频
     */
    @PutMapping("/{contentId}/video")
    @SystemLog(operation = "更新内容视频")
    public ResponseEntity<ApiResponse<String>> updateVideo(
            @PathVariable Long contentId,
            @Valid @ModelAttribute VideoUpdateRequestDTO requestDTO) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户更新视频请求，用户ID: {}, 内容ID: {}", userId, contentId);

        contentService.updateVideo(contentId, requestDTO.getVideo(), userId);
        return ResponseEntity.ok(ApiResponse.success("视频更新任务已提交，正在处理中"));
    }

    /**
     * 批量更新图片
     */
    @PutMapping("/{contentId}/images")
    @SystemLog(operation = "批量更新内容图片")
    public ResponseEntity<ApiResponse<String>> updateImages(
            @PathVariable Long contentId,
            @ModelAttribute ImagesUpdateRequestDTO requestDTO) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户批量更新图片请求，用户ID: {}, 内容ID: {}, 删除数量: {}, 新增数量: {}",
                userId, contentId,
                requestDTO.getDeleteImageIds() != null ? requestDTO.getDeleteImageIds().size() : 0,
                requestDTO.getNewImages() != null ? requestDTO.getNewImages().length : 0);

        contentService.updateImages(contentId, requestDTO.getDeleteImageIds(),
                requestDTO.getNewImages(), userId);
        return ResponseEntity.ok(ApiResponse.success("图片批量更新任务已提交，正在处理中"));
    }

    /**
     * 获取内容的媒体文件
     */
    @GetMapping("/{contentId}/media")
    @SystemLog(operation = "查询内容媒体文件")
    public ResponseEntity<ApiResponse<ContentMediaDTO>> getContentMedia(@PathVariable Long contentId) {
        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户查询内容媒体文件，用户ID: {}, 内容ID: {}", userId, contentId);

        ContentMediaDTO mediaDTO = contentService.getContentMedia(contentId, userId);
        return ResponseEntity.ok(ApiResponse.success("查询成功", mediaDTO));
    }

    /**
     * 获取操作日志历史
     */
    @GetMapping("/operation-logs")
    @SystemLog(operation = "查询操作日志历史")
    public ResponseEntity<ApiResponse<OperationLogHistoryResponse>> getOperationLogHistory(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "operationType", required = false) String operationType,
            @RequestParam(value = "contentId", required = false) Long contentId,
            @RequestParam(value = "userId", required = false) Long userId) {

        // 获取当前用户信息
        Long currentUserId = authService.getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        String currentUserRole = authService.getCurrentUserRole();

        log.info("用户查询操作日志历史，当前用户ID: {}, 角色: {}, 查询用户ID: {}, 内容ID: {}, 操作类型: {}, 页码: {}, 大小: {}",
                currentUserId, currentUserRole, userId, contentId, operationType, page, size);

        OperationLogHistoryResponse response = operationLogService.getOperationLogHistory(
                page, size, operationType, contentId, userId, currentUserId, currentUserRole);

        return ResponseEntity.ok(ApiResponse.success("查询成功", response));
    }

    /**
     * 获取用户自己的内容列表
     */
    @GetMapping("/my")
    @SystemLog(operation = "查询用户自己的内容列表")
    public ResponseEntity<ApiResponse<ContentListResponse>> getUserContentList(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "textContent", required = false) String textContent,
            @RequestParam(value = "contentType", required = false) String contentType,
            @RequestParam(value = "orderBy", required = false) String orderBy) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户查询自己的内容列表，用户ID: {}, 页码: {}, 大小: {}, 标题: {}, 内容: {}, 类型: {}, 排序: {}",
                userId, page, size, title, textContent, contentType, orderBy);

        ContentListResponse response = contentService.getUserContentList(
                page, size, title, textContent, contentType, orderBy, userId);

        return ResponseEntity.ok(ApiResponse.success("查询成功", response));
    }

    /**
     * 获取所有内容列表（管理员使用）
     */
    @GetMapping("/admin")
    @SystemLog(operation = "管理员查询所有内容列表")
    public ResponseEntity<ApiResponse<ContentListResponse>> getAdminContentList(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "textContent", required = false) String textContent,
            @RequestParam(value = "contentType", required = false) String contentType,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "userId", required = false) Long userId) {

        // 获取当前用户信息
        Long currentUserId = authService.getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 权限验证：只有管理员可以查看所有内容
        if (!authService.isCurrentUserAdmin()) {
            return ResponseEntity.ok(ApiResponse.fail("权限不足，只有管理员可以查看所有内容"));
        }

        log.info("管理员查询所有内容列表，管理员ID: {}, 页码: {}, 大小: {}, 标题: {}, 内容: {}, 类型: {}, 排序: {}, 用户ID: {}",
                currentUserId, page, size, title, textContent, contentType, orderBy, userId);

        ContentListResponse response = contentService.getAdminContentList(
                page, size, title, textContent, contentType, orderBy, userId, currentUserId);

        return ResponseEntity.ok(ApiResponse.success("查询成功", response));
    }

    /**
     * 获取公开内容列表（用户查看所有公开内容）
     */
    @GetMapping("/public")
    @SystemLog(operation = "查询公开内容列表")
    public ResponseEntity<ApiResponse<ContentListResponse>> getPublicContentList(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "textContent", required = false) String textContent,
            @RequestParam(value = "contentType", required = false) String contentType,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "userId", required = false) Long userId) {

        // 获取当前用户ID（可选，游客也可以访问）
        Long currentUserId = authService.getCurrentUserId();

        log.info("查询公开内容列表，当前用户ID: {}, 页码: {}, 大小: {}, 标题: {}, 内容: {}, 类型: {}, 排序: {}, 筛选用户ID: {}",
                currentUserId, page, size, title, textContent, contentType, orderBy, userId);

        ContentListResponse response = contentService.getPublicContentList(
                page, size, title, textContent, contentType, orderBy, userId, currentUserId);

        return ResponseEntity.ok(ApiResponse.success("查询成功", response));
    }

    /**
     * 浏览内容详情
     */
    @GetMapping("/{contentId}/view")
    @SystemLog(operation = "浏览内容")
    public ResponseEntity<ApiResponse<ContentViewDTO>> viewContent(@PathVariable Long contentId) {

        // 获取当前用户ID（游客也可以浏览，但不会记录行为）
        Long userId = authService.getCurrentUserId();

        log.info("用户浏览内容请求，用户ID: {}, 内容ID: {}", userId, contentId);

        ContentViewDTO viewDTO = contentService.viewContent(contentId, userId);
        return ResponseEntity.ok(ApiResponse.success("浏览成功", viewDTO));
    }

    /**
     * 更新内容的标题和文本内容
     */
    @PutMapping("/{contentId}/text")
    @SystemLog(operation = "更新内容文本")
    public ResponseEntity<ApiResponse<String>> updateContentText(
            @PathVariable Long contentId,
            @Valid @RequestBody ContentTextUpdateRequestDTO requestDTO) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        log.info("用户更新内容文本请求，用户ID: {}, 内容ID: {}, 标题: {}", userId, contentId, requestDTO.getTitle());

        contentService.updateContentText(contentId, requestDTO.getTitle(), requestDTO.getTextContent(), userId);
        return ResponseEntity.ok(ApiResponse.success("内容文本更新成功"));
    }

    /**
     * 删除内容（软删除）
     */
    @DeleteMapping("/{contentId}")
    @SystemLog(operation = "删除内容")
    public ResponseEntity<ApiResponse<String>> deleteContent(@PathVariable Long contentId) {

        // 获取当前用户ID
        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 获取当前用户权限
        boolean isAdmin = authService.isCurrentUserAdmin();

        log.info("用户删除内容请求，用户ID: {}, 内容ID: {}, 是否管理员: {}", userId, contentId, isAdmin);

        contentService.updatePublishStatus(contentId, false, userId, isAdmin);
        return ResponseEntity.ok(ApiResponse.success("内容删除成功"));
    }
}